﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Web;
using Microsoft.Win32;
using System.Diagnostics;
using System.Threading;

namespace NewsSpider.Utility
{
    /// <summary>
    /// 版权所有: 版权所有(C) 2012，上海云里网络科技有限公司
    /// 内容摘要: 本类主要封装了日常较通用的功能模块，如果不是通用功能，不要加入此类。
    /// 完成日期：2011年4月13日
    /// 版    本：V1.0 
    /// 作    者：Adin
    /// 
    /// 修改记录1: 
    /// 修改日期：2011年4月14日
    /// 版 本 号：V1.1
    /// 修 改 人：Adin
    /// 修改内容：对代码规范进行修改，使代码更容易阅读，更容易维护
    /// 修改记录2: 
    /// 修改日期：2011年4月15日
    /// 版 本 号：V1.2
    /// 修 改 人：Adin
    /// 修改内容：移除了一些方法，分割成独立的类
    /// </summary>
    public class CommonHelper
    {
        //SQLite数据库密码
        public static string SQLITEPASSWORD="cloudin53344521";
        //保存自定义文件格式加密密码
        public static string SEOFILEPASSWORD = "cloudin53344521";

        public static string strApplicationName = "";
        public static bool bValue = false;

        //随机字母
        private static char[] arWords = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
        //随机数字
        private static char[] arNumeric = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };


        /// <summary>
        /// 获取随机字母
        /// </summary>
        /// <param name="iLength">所需生成随机字母的长度</param>
        /// <example>CommonHelper.GenerateRandomWords(4)，取得随机字母为：edge</example>
        /// <returns>返回随机字母</returns>
        public static string GenerateRandomWords(int iLength)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(26);
            Random rm = new Random();
            for (int i = 0; i < iLength; i++)
            {
                sb.Append(arWords[rm.Next(26)]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 0~9数字中生成任意长度数字
        /// </summary>
        /// <param name="iLength"></param>
        /// <example>CommonHelper.GenerateRandomWords(4)，取得随机字母为：edge</example>
        /// <returns>返回随机数字</returns>
        public static string GenerateRandomNum(int iLength)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(10);
            Random rm = new Random();
            for (int i = 0; i < iLength; i++)
            {
                sb.Append(arNumeric[rm.Next(10)]);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 关闭应用程序进程
        /// </summary>
        /// <param name="sender">object 对象</param>
        /// <param name="e">事件参数</param>
        public static void ApplicationExit(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DialogResult result = MessageBox.Show("您确认要退出吗？", "确认退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result == DialogResult.OK)
            {
                System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("SEO.KeywordsAnalysis");
                foreach (System.Diagnostics.Process pro in proc)//关闭原有应用程序的所有进程 
                {
                    pro.Kill();
                }

                Application.Exit();
                Process.GetCurrentProcess().Kill();
            }
            else
            {
                e.Cancel = true;
            }
        }


        public static void ApplicationExitForEDM(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DialogResult result = MessageBox.Show("您确认要退出吗？", "确认退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result == DialogResult.OK)
            {
                System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName("SEO.EDM");
                foreach (System.Diagnostics.Process pro in proc)//关闭原有应用程序的所有进程 
                {
                    pro.Kill();
                }

                Application.Exit();
                //Process.GetCurrentProcess().Kill();
            }
            else
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 退出应用程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void ApplicationExitForCommon(object sender, System.ComponentModel.CancelEventArgs e)
        {
            DialogResult result = MessageBox.Show("您确认要退出吗？", "确认退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (result == DialogResult.OK)
            {
                System.Diagnostics.Process[] proc = System.Diagnostics.Process.GetProcessesByName(strApplicationName);
                foreach (System.Diagnostics.Process pro in proc)//关闭原有应用程序的所有进程 
                {
                    pro.Kill();
                }

                Application.Exit();
                if (bValue)
                {
                    Process.GetCurrentProcess().Kill();
                }
            }
            else
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 退出整个应用程序
        /// </summary>
        public static void ApplicationExit()
        {
            System.Diagnostics.Process[] arProcess = System.Diagnostics.Process.GetProcessesByName("SEO.KeywordsAnalysis");
            foreach (System.Diagnostics.Process ps in arProcess)//关闭原有应用程序的所有进程 
            {
                ps.Kill();
            }

            Application.Exit();
            Process.GetCurrentProcess().Kill();
        }

        /// <summary>
        /// 获取当前软件皮肤
        /// </summary>
        /// <returns>返回软件皮肤路径文件</returns>
        public static string GetCurrentSoftSkin()
        {
            return Application.StartupPath + "\\skin\\Calmness.ssk";
        }

        /// <summary>
        /// MD5加密字符串
        /// </summary>
        /// <param name="strContent">字符串</param>
        /// <param name="iCodeNum">可选择16或32，即加密后的密文16位或32位</param>
        /// <returns>返回加密字符串</returns>
        public static string MD5(string strContent, int iCodeNum)
        {
            string strReturnValue = "";

            if (iCodeNum == 16) //16位MD5加密（取32位加密的9~25字符） 
            {
                strReturnValue = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strContent, "MD5").ToLower().Substring(8, 16);
            }

            if (iCodeNum == 32) //32位加密 
            {
                strReturnValue = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strContent, "MD5").ToLower();
            }

            return strReturnValue;
        }

        /// <summary>
        /// 弹窗消息框，加载当前页面
        /// </summary>
        /// <param name="strPopupMessage">弹窗消息内容</param>
        public static void ReloadPage(string strPopupMessage)
        {
            HttpContext.Current.Response.Write("<script language=javascript>alert('" + strPopupMessage + "');</script> ");
        }

        /// <summary>
        /// 重定向到当前页面，相当于重新打开本页面
        /// </summary>
        /// <param name="strPopupMessage">弹窗消息内容</param>
        public static void ReloadCurrentPage(string strPopupMessage)
        {
            string strUrl = HttpContext.Current.Request.Url.ToString();
            strUrl = strUrl.Replace("'", " ");
            HttpContext.Current.Response.Write("<script language=javascript>alert('" + strPopupMessage + "');window.window.location.href='" + strUrl + "';</script>");
        }

        /// <summary>
        /// 重定向一个指定的页面
        /// </summary>
        /// <param name="strPopupMessage">弹窗消息内容</param>
        /// <param name="strSpecialPageUrl">指定页面地址</param>
        public static void ReloadCurrentPage(string strPopupMessage, string strSpecialPageUrl)
        {
            HttpContext.Current.Response.Write(" <script language=javascript>alert('" + strPopupMessage + "');window.window.location.href='" + strSpecialPageUrl + "';</script> ");
        }

        /// <summary>
        /// 获取当前是星期几（汉字）
        /// </summary>
        /// <returns></returns>
        public static string GetWeekName()
        {
            //获取当前日期是星期几
            string dt = DateTime.Today.DayOfWeek.ToString();
            //根据取得的星期英文单词返回汉字
            string strWeekName = "";
            switch (dt)
            {
                case "Monday":
                    strWeekName = "星期一";
                    break;

                case "Tuesday":
                    strWeekName = "星期二";
                    break;

                case "Wednesday":
                    strWeekName = "星期三";
                    break;

                case "Thu;rsday":
                    strWeekName = "星期四";
                    break;

                case "Friday":
                    strWeekName = "星期五";
                    break;

                case "Saturday":
                    strWeekName = "星期六";
                    break;

                case "Sunday":
                    strWeekName = "星期日";
                    break;

            }

            return strWeekName;
        }

        /// <summary>
        /// 存储Cookie值
        /// </summary>
        /// <param name="strKey">Cookie名称</param>
        /// <param name="strValue">Cookie值</param>
        /// <param name="iExpiresDays">过期时间，天为单位</param>
        public static void SaveCookie(string strKey, string strValue, int iExpiresDays)
        {
            DateTime dt = DateTime.Now.AddDays(iExpiresDays);
            HttpCookie hc = new HttpCookie(strKey);
            //hc.Domain = ".yourdomain.com";
            hc.Value = HttpUtility.UrlEncode(strValue);
            hc.Expires = dt;
            HttpContext.Current.Response.Cookies.Add(hc);
        }


        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="strCookieName">Cookie名</param>
        /// <param name="strCookieValue">Cookie值</param>
        /// <param name="iDayNum">Cookie保存天数，以天为单位</param>
        public static void SetCookie(string strCookieName, string strCookieValue, int iDayNum)
        {
            HttpCookie cookie = new HttpCookie(strCookieName);
            cookie.Value = HttpContext.Current.Server.UrlEncode(strCookieValue);
            //cookie.Domain = ".yourdomain.com";
            DateTime dt = DateTime.Now;
            cookie.Expires = dt.AddDays(iDayNum);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }


        /// <summary>
        /// 获取Cookie值
        /// </summary>
        /// <param name="strCookieName">Cookie名</param>
        /// <param name="bDecode">是否解密</param>
        /// <returns>返回Cookie值</returns>
        public static String GetCookieString(string strCookieName, bool bDecode)
        {
            if (HttpContext.Current.Request.Cookies[strCookieName] == null)
            {
                return String.Empty;
            }
            try
            {
                string strCookieValue = HttpContext.Current.Request.Cookies[strCookieName].Value.ToString();
                if (bDecode)
                {
                    strCookieValue = HttpContext.Current.Server.UrlDecode(strCookieValue);
                }
                return strCookieValue;
            }
            catch
            {
                return String.Empty;
            }
        }

        /// <summary>
        /// 从Cookie中获取整型值
        /// </summary>
        /// <param name="strCookieName">Cookie名</param>
        /// <returns>返回整型值</returns>
        public static int GetCookieInt(string strCookieName)
        {
            string strCookieValue= GetCookieString(strCookieName, true);
            if (!string.IsNullOrEmpty(strCookieValue))
            {
                return Convert.ToInt32(strCookieValue);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 获取Cookie ID
        /// </summary>
        /// <param name="strCookieName">Cookie名</param>
        /// <returns>返回Cookie ID</returns>
        public static string GetCookid(string strCookieName)
        {
            Encoding eg = Encoding.GetEncoding("UTF-8");
            return HttpUtility.UrlDecode(strCookieName, eg);
        }

        /// <summary>
        /// 显示Flash
        /// </summary>
        /// <param name="strSWFURL">SWF文件地址</param>
        /// <param name="iWidth">显示宽度</param>
        /// <param name="iHeight">显示高度</param>
        /// <returns></returns>
        public static string ShowFlash(string strSWFURL, int iWidth, int iHeight)
        {
            string strHtmlString = "<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0\" width=\"" + iWidth + "px\" height=\"" + iHeight + "px\"  id=\"Flash\" align=\"middle\">";
            strHtmlString += "<param name=\"allowScriptAccess\" value=\"sameDomain\" />";
            strHtmlString += "<param name=\"allowFullScreen\" value=\"false\" />";
            strHtmlString += "<param name=\"movie\" value=\"" + strSWFURL + "\" />";
            strHtmlString += "<param name=\"quality\" value=\"high\" />";
            strHtmlString += "<param name=wmode value=transparent>";
            strHtmlString += "<embed src=\"" + strSWFURL + "\" quality=\"high\" width=\"" + iWidth + "px\" height=\"" + iHeight + "px\" align=\"middle\" allowScriptAccess=\"sameDomain\" allowFullScreen=\"false\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />";
            strHtmlString += "</object>";

            return strHtmlString;
        }

        /// <summary> 
        /// 开机启动项 
        /// </summary> 
        /// <param name="bIsAutoRun">是否启动</param> 
        /// <param name="strFileName">启动值的名称</param> 
        /// <param name="strFilePath">启动程序的路径</param> 
        public static void SetRunStart(bool bIsAutoRun,string strFileName,string strFilePath)
        {
            RegistryKey rk = null;
            try
            {
                rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (rk == null)
                {
                    rk = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                }
                if (bIsAutoRun)
                {
                    rk.SetValue(strFileName, strFilePath);
                }
                else
                {
                    rk.SetValue(strFileName, false);
                }
            }
            catch (Exception ex)
            {
                NewsSpider.Utility.Log.SaveErrorLog("设置开机启动项 -> " + ex.Message);
            }
            finally
            {
                if (rk != null)
                {
                    rk.Close();
                }
            }
        }

        /// <summary>
        /// 获取图片路径
        /// </summary>
        /// <param name="strPath">路径</param>
        /// <returns></returns>
        public static System.Drawing.Image GetImage(string strPath)
        {
            return System.Drawing.Image.FromFile(@Application.StartupPath + "\\" + strPath);
        }

        /// <summary>
        /// 隐藏IP地址最后一位用*号代替
        /// </summary>
        /// <param name="strIpAddress">IP地址如：192.168.1.1</param>
        /// <returns>返回192.168.1.*</returns>
        public static string HidenLastIp(string strIpAddress)
        {
            return strIpAddress.Substring(0, strIpAddress.LastIndexOf(".")) + ".*";
        }

        /// <summary>
        /// 抓取手机号码归属地
        /// </summary>
        /// <param name="strPhone">手机号码</param>
        /// <returns>返地址信息</returns>
        public static string GetPhoneAddress(string strPhone)
        {
            string strReturnValue = "";
            try
            {

                WebClient wc = new WebClient();
                wc.Encoding = System.Text.Encoding.GetEncoding("gb2312");
                wc.OpenRead("http://www.ip138.com:8080/search.asp?action=mobile&mobile=" + strPhone);
                //Gets html code
                string strGetHtmlCode = wc.RespHtml;
                strGetHtmlCode = strGetHtmlCode.Replace("卡号归属地", "<--start-->");
                strGetHtmlCode = strGetHtmlCode.Replace("卡&nbsp;类&nbsp;型", "<--end-->");

                Regex rx = new Regex("<--start-->(?<content>[\\s\\S]*)?<--end-->", RegexOptions.Singleline);
                string strGetInfo = rx.Match(strGetHtmlCode).Result("${content}");
                strGetInfo = StringHelper.CleanHtml(strGetInfo).Trim();
                strGetInfo = strGetInfo.Replace("&nbps;", " ");


                if (string.IsNullOrEmpty(strGetInfo))
                {
                    strReturnValue = "未知";
                }
                else
                {
                    strReturnValue = strGetInfo;
                }
            }
            catch (Exception ex)
            {
               Log.SaveErrorLog("抓取手机号码归属地 -> " + ex.Message);
            }

            return strReturnValue;
        }

        /// <summary>
        /// 根据IP地址获取物理地址
        /// </summary>
        /// <param name="strIP">IP地址</param>
        /// <returns>返回物理地址</returns>
        public static string GetIPAddress(string strIP)
        {
            string strReturnValue = "";
            
            try
            {
                string strLink = "http://www.ip138.com/ips.asp?action=2&ip=" + strIP;
                WebClient client2 = new WebClient();
                client2.Encoding = System.Text.Encoding.GetEncoding("gb2312");
                client2.OpenRead(strLink);
                //Gets html code
                string strGetHtmlCode = client2.RespHtml;

                Regex address = new Regex("<ul class=\"ul1\">(?<content>[\\s\\S]*)?</li></ul></td>", RegexOptions.Singleline);
                string GetAddress = address.Match(strGetHtmlCode).Result("${content}");

                Regex address2 = new Regex("本站主数据：(?<content>[\\s\\S]*)?</li><li>参考数据一", RegexOptions.Singleline);
                GetAddress = address2.Match(GetAddress).Result("${content}");

                if (string.IsNullOrEmpty(GetAddress))
                {
                    strReturnValue = "未知";
                }
                else
                {
                    strReturnValue = GetAddress;
                }
            }
            catch (Exception ex)
            {
                Log.SaveErrorLog("根据IP地址获取物理地址 -> " + ex.Message);
            }

            return strReturnValue;
        }

        /// <summary>
        /// 获取当前IP地址
        /// </summary>
        /// <returns>返回当前IP地址</returns>
        public static string GetIPAddress()
        {
            string returnValue = "";
            try
            {
                WebClient client = new WebClient();
                client.Encoding = System.Text.Encoding.GetEncoding("gb2312");
                client.OpenRead("http://www.ip138.com/ip2city.asp");
                //Gets html code
                string strGetHtmlCode = client.RespHtml;

                strGetHtmlCode = strGetHtmlCode.Replace("[", "<start>");
                strGetHtmlCode = strGetHtmlCode.Replace("]", "<end>");

                Regex ip = new Regex("<start>(?<content>[\\s\\S]*)?<end>", RegexOptions.Singleline);
                returnValue = ip.Match(strGetHtmlCode).Result("${content}");

            }
            catch (Exception ex)
            {
                NewsSpider.Utility.Log.SaveErrorLog("获取IP地址 -> "+ex.Message);
            }

            return returnValue;
        }

        /// <summary>
        /// 格式化显示价格数据，如：1000000.00 格式化后为：1,000,000.00
        /// </summary>
        /// <param name="strPrice">价格</param>
        /// <returns>返回格式化数据</returns>
        public static string FormatPriceViewData(string strPrice)
        {
            string strReturnValue = "";
            string strNewPrice = strPrice;
            if (!strPrice.Contains("."))
            {
                strPrice = strPrice + ".00";
            }

            if (strPrice.Contains("-"))
            {
                strPrice = strPrice.Replace("-", "");
            }

            string[] splitPrice = strPrice.Split(new char[] { '.' });
            string strFormatPrice = splitPrice[0].ToString();
            int nLength = strFormatPrice.Length;
            string strNewFormatPrice = "";
            switch (nLength)
            {
                case 3: strNewFormatPrice = strFormatPrice;
                    break;
                case 4: strNewFormatPrice = strFormatPrice.Insert(1, ",");
                    break;
                case 5: strNewFormatPrice = strFormatPrice.Insert(2, ",");
                    break;
                case 6: strNewFormatPrice = strFormatPrice.Insert(3, ",");
                    break;
                case 7:
                    strNewFormatPrice = strFormatPrice.Insert(1, ",");
                    strNewFormatPrice = strNewFormatPrice.Insert(5, ",");
                    break;
                case 8:
                    //10000000.00 -> 10,000,000.00
                    strNewFormatPrice = strFormatPrice.Insert(2, ",");
                    strNewFormatPrice = strNewFormatPrice.Insert(6, ",");
                    break;
                case 9:
                    //100000000.00 -> 100,000,000.00
                    strNewFormatPrice = strFormatPrice.Insert(3, ",");
                    strNewFormatPrice = strNewFormatPrice.Insert(7, ",");
                    break;
                case 10:
                    //1000000000.00 -> 1,000,000,000.00
                    strNewFormatPrice = strFormatPrice.Insert(1, ",");
                    strNewFormatPrice = strNewFormatPrice.Insert(5, ",");
                    strNewFormatPrice = strNewFormatPrice.Insert(9, ",");
                    break;
                default:
                    strNewFormatPrice = strFormatPrice;
                    break;

            }

            strReturnValue = strNewFormatPrice + ".00";
            if (strNewPrice.Contains("-"))
            {
                strReturnValue = "-" + strReturnValue;
            }

            return strReturnValue;
        }

        /// <summary>
        /// SQL注入过滤
        /// </summary>
        /// <param name="strInText">要过滤的字符串</param>
        /// <returns>如果参数存在不安全字符，则返回true</returns>
        public static bool SqlFilter2(string strInText)
        {
            string strWord = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join";
            if (strInText == null)
                return false;
            foreach (string i in strWord.Split('|'))
            {
                if ((strInText.ToLower().IndexOf(i + " ") > -1) || (strInText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 截取内容中的图片
        /// </summary>
        /// <param name="content">文章内容</param>
        /// <returns></returns>
        public static string GetContentImage(string content)
        {
            Regex reg = new Regex(@"img[^>]*?src=""?(?<url>[a-z][^\s""]*)""?", RegexOptions.IgnoreCase);

            Match mr = reg.Match(content);
            string url = "";

            url = mr.Groups[1].ToString();

            return url;
        }

        /// <summary>
        /// 指定内容获取指定的长度，超过指定长度用“..”代替
        /// 通常用于显示文章最新几条，指定了文章字符长度。
        /// </summary>
        /// <param name="content">文章标题</param>
        /// <param name="len">指定长度</param>
        /// <param name="adddot">是否需要用..来代替超长的字符，如果需要True，不需要False</param>
        /// <returns>返回处理后的字符串</returns>
        public static string LimitString(object content, int len, bool adddot)
        {
            string originalNews = content.ToString().Trim();
            System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
            byte[] newsBytes = encoding.GetBytes(originalNews);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            int narrowChars = 0;
            int widthChars = 0;
            for (int i = 1; i < newsBytes.Length; i += 2)
            {
                if (widthChars == len)
                    break;
                byte[] temp = new byte[] { newsBytes[i - 1], newsBytes[i] };
                sb.Append(System.Text.Encoding.Unicode.GetString(temp));
                if ((int)newsBytes[i] == 0)
                {
                    narrowChars++;
                    if (narrowChars == 2)
                    {
                        narrowChars = 0;
                        widthChars++;
                    }
                }
                else
                {
                    widthChars++;
                }
            }
            if (adddot && sb.ToString() != content.ToString())
            {
                return sb.ToString() + "..";
            }
            return sb.ToString();
        }

        /// <summary>
        /// 获取表情图片，用于文字间
        /// </summary>
        /// <returns>返回表情图片</returns>
        public static string GetFacePics()
        {
            string[] arrPics = { "[心]", "[太阳]", "[花心]", "[good]", "[ok]", "[来]", "[给力]", "[围观]", "[粉红丝带]", "[爱心传递]", "[鲜花]", "[花]", "[耶]", "[跳舞花]", "[冒个泡]" };
            Random rm = new Random();
            return arrPics[rm.Next(1, 15)].ToString();
        }

        /// <summary>
        /// 获取表情图片，用于句尾
        /// </summary>
        /// <returns>返回表情图片</returns>
        public static string GetFacePicsEnd()
        {
            string[] arrPics = { "[心]", "[太阳]", "[花心]", "[good]", "[ok]", "[来]", "[给力]", "[围观]", "[爱心传递]", "[鲜花]", "[花]", "[耶]", "[跳舞花]" };
            Random rm = new Random();
            return arrPics[rm.Next(1, 13)].ToString();
        }


        /// <summary>
        /// 获取魔法表情，用于微博句末
        /// </summary>
        /// <returns>返回魔法表情</returns>
        public static string GetMagicFace()
        {
            string[] arrPics = { "http://t.cn/GZ7Sw", "http://t.cn/GZPZB", "http://t.cn/bR6v5", "http://t.cn/bR56p", "http://t.cn/GZv51", "http://t.cn/GZzk2 ", "http://t.cn/GU3Ok", "http://t.cn/GZzrp" };
            Random rm = new Random();
            return arrPics[rm.Next(1, 9)].ToString();
        }

        /// <summary>
        /// 清除IE缓存
        /// </summary>
        public static void ClearIECache()
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = "/c " + "del /f /s /q \"%userprofile%\\Local Settings\\Temporary Internet Files\\*.*\"";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            string result = process.StandardOutput.ReadToEnd();
        }

        /// <summary>
        /// 清除IE Cookie
        /// </summary>
        public static void ClearIECookie()
        {
            Process process = new Process();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.Arguments = "/c " + "del /f /s /q \"%userprofile%\\Cookies\\*.*\"";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
            string result = process.StandardOutput.ReadToEnd();
        }

        /// <summary>
        /// 关闭IE窗口
        /// </summary>
        public static void KillIEWindows()
        {
            Process[] process = Process.GetProcesses();
            for (int i = 0; i < process.Length; i++)
            {
                if (process[i].ProcessName.ToLower() == "iexplore")
                {
                    try
                    {
                        process[i].Kill();
                        Thread.Sleep(500);
                    }
                    catch
                    {
                    }
                }
            }
        }

        /// <summary>
        /// 检测是否是电子邮件
        /// </summary>
        /// <param name="strEmail">电子邮件</param>
        /// <returns>True or False </returns>
        public static bool CheckIsEmail(string strEmail)
        {
            String EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            Regex regex = new Regex(EmailPattern, RegexOptions.IgnoreCase);
            if (regex.Match(strEmail).Success)
            {
                //验证特殊格式
                if (strEmail.Contains("@"))
                {
                    string[] splitEmail = strEmail.Split(new char[] {'@'});
                    string strFirstEmail = splitEmail[0];
                    if (strFirstEmail.Length >= 15)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取问候语
        /// </summary>
        /// <returns></returns>
        public static string GetWenHouYu()
        {
            string strReturnValue = "";

            if (DateTime.Now.Hour >= 0 && DateTime.Now.Hour <= 8)
            {
                strReturnValue = "早晨好，新的一天开始了，祝您顺顺利利！";
            }
            if (DateTime.Now.Hour >= 9 && DateTime.Now.Hour <= 12)
            {
                strReturnValue = "上午好，紧张的工作，别忘记休息噢！";
            }
            if (DateTime.Now.Hour >= 13 && DateTime.Now.Hour <= 18)
            {
                strReturnValue = "下午好，有空坐下来喝喝下午茶，调养身体！";
            }
            if (DateTime.Now.Hour >= 19 && DateTime.Now.Hour <= 21)
            {
                strReturnValue = "晚上好，看看电视，陪家人聊聊天，美好的一天又结束啦！";
            }
            if (DateTime.Now.Hour >= 22 && DateTime.Now.Hour <= 23)
            {
                strReturnValue = "夜深了，注意身体，早点休息噢！";
            }

            return strReturnValue;
        }

    }     
}
